package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCarMapper shoppingCarMapper;
    @Autowired
    private OrdersMapper ordersMapper;//订单表
    @Autowired
    private OrderDetailMapper orderDetailMapper;//订单明细表
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;//微信支付工具
    @Autowired
    private WebSocketServer webSocketServer;

    @Value("${sky.shop.address}")
    private String shopAddress;
    @Value("${sky.baidu.ak}")
    private String ak;

    /**
     * 检查客户的收货地址是否超出配送范围
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address",shopAddress);
        map.put("output","json");
        map.put("ak",ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address",address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }

   //用户提交订单
    @Transactional//开启事务
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //排除异常情况(地址是否为空，购物车是否有数据)
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());//获取地址信息
        if(addressBook == null ){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //检查用户地址是否在配送范围
        checkOutOfRange(addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());

        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCars =shoppingCarMapper.getShoppingCar(shoppingCart);//查询购物车
        if(shoppingCars == null || shoppingCars.size() == 0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //1.向订单表中插入一条订单信息
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setUserId(BaseContext.getCurrentId());//下单人的id
        orders.setOrderTime(LocalDateTime.now());//下单时间
        orders.setAddress(addressBook.getDetail());//获取地址
        orders.setConsignee(addressBook.getConsignee());//获取收货人
        orders.setPhone(addressBook.getPhone());//获取收货人手机号
        orders.setPayStatus(Orders.UN_PAID);//订单支付状态
        orders.setStatus(Orders.PENDING_PAYMENT);//订单状态
        orders.setNumber(String.valueOf(System.currentTimeMillis()));//订单号
        ordersMapper.insert(orders);//插入订单数据
        //2.向订单详情表添加n条信息
        List<OrderDetail> list = new ArrayList<>();
        for (ShoppingCart shoppingCart1 : shoppingCars){
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orders.getId());//订单id
            BeanUtils.copyProperties(shoppingCart1,orderDetail);//把购物车信息复制给订单明细
            list.add(orderDetail);
        }
        orderDetailMapper.inserts(list);//批量插入订单明细信息
        //3.清空购物车(通过用户id清空)
        shoppingCarMapper.deleteByUserId(BaseContext.getCurrentId());//清空购物车
        //4.提交订单返回相关信息
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());//订单id
        orderSubmitVO.setOrderNumber(orders.getNumber());//订单号
        orderSubmitVO.setOrderTime(orders.getOrderTime());//下单时间
        orderSubmitVO.setOrderAmount(orders.getAmount());
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );

//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));

        //取消支付的方式
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code","ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        //为替代微信支付成功后的数据库订单状态更新，多定义一个方法进行修改
        Integer OrderPaidStatus = Orders.PAID; //支付状态，已支付
        Integer OrderStatus = Orders.TO_BE_CONFIRMED;  //订单状态，待接单
        //发现没有将支付时间 check_out属性赋值，所以在这里更新
        LocalDateTime check_out_time = LocalDateTime.now();
        ordersMapper.updateStatus(OrderStatus, OrderPaidStatus, check_out_time, ordersPaymentDTO.getOrderNumber());

        //添加订单提醒给商家前端页面
        Map map = new HashMap<>();
        map.put("type",1);//1为来电提醒
        map.put("orderId",ordersPaymentDTO.getOrderNumber());//订单号
        map.put("content","订单:"+ordersPaymentDTO.getOrderNumber()+"请及时查收");
        String jsonString = JSONObject.toJSONString(map);//变化成json字符串
        webSocketServer.sendToAllClient(jsonString);//发送给商家订单消息

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = ordersMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
    }

    //历史订单查询
    public PageResult historyOrders(int page, int pageSize, Integer status) {
        OrdersPageQueryDTO dto = new OrdersPageQueryDTO();
        dto.setStatus(status);
        //1.获取用户啊id
        Long userId = BaseContext.getCurrentId();
        dto.setUserId(userId);
        //2.设置分页查询相关信息
        PageHelper.startPage(page,pageSize);
        // 3.订单和订单详情进行多表联合查询
        List<OrderVO> list = ordersMapper.getOrders(dto);
        Page<OrderVO> p = (Page<OrderVO>)list;
        //4.封装成pageResult
        PageResult result = new PageResult();
        result.setTotal(p.getTotal());
        result.setRecords(p.getResult());
        return result;
    }

    //根据订单id，查询订单详情
    public OrderVO orderDetails(Long id) {
        OrderVO orderVO = ordersMapper.getOrderDetailsById(id);
        return orderVO;
    }

    //根据订单id，取消订单
    public void cancelOrder(Long id) {
        //1.根据id查询相关的信息
        OrderVO orderVO = ordersMapper.getOrderDetailsById(id);
        if(orderVO == null){//订单是否存在
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //2.当信息不为空时，判断订单的状态如果订单状态为1、2则可以取消
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if(orderVO.getStatus() > 2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setStatus(Orders.CANCELLED);
        //4.订单处于待接单状态则退款
//        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
//            //调用微信支付退款接口
//            weChatPayUtil.refund(
//                    ordersDB.getNumber(), //商户订单号
//                    ordersDB.getNumber(), //商户退款单号
//                    new BigDecimal(0.01),//退款金额，单位 元
//                    new BigDecimal(0.01));//原订单金额
//
//            //支付状态修改为 退款
//            orders.setPayStatus(Orders.REFUND);
//        }
        if (orderVO.getStatus().equals(Orders.TO_BE_CONFIRMED)){//支付状态修改为退款
            orders.setPayStatus(Orders.REFUND);
        }

        //5.修改订单的状态
        orders.setId(id);//订单id
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());//取消时间

        ordersMapper.update(orders);

    }

    //根据订单id再次下单
    public void repetition(Long id) {
        //1.根据订单id查询订单详细表，获得订单详情信息
        List<OrderDetail> orderDetails = orderDetailMapper.getDetailById(id);
        Long userId = BaseContext.getCurrentId();//获取当前用户id
        //2.把商品信息加入购物车
        List<ShoppingCart> shoppingCars = orderDetails.stream().map(new Function<OrderDetail, ShoppingCart>() {
            @Override
            public ShoppingCart apply(OrderDetail orderDetail) {
                ShoppingCart shoppingCart = new ShoppingCart();
                BeanUtils.copyProperties(orderDetail, shoppingCart);
                shoppingCart.setUserId(userId);//设置用户id
                shoppingCart.setCreateTime(LocalDateTime.now());//创建时间
                return shoppingCart;
            }
        }).collect(Collectors.toList());//利用stream流把订单详情信息转化为购物车信息
        //将购物车数据批量插入
        shoppingCarMapper.insertBatch(shoppingCars);

    }

    //商家条件查询订单
    public PageResult condditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        //设置分页查询插件
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //执行查询订单信息及详情信息的多表分页查询
        List<OrderVO> orders = ordersMapper.getOrders(ordersPageQueryDTO);
        //遍历orders，把每个订单的详情的菜名和数量变成字符串
        for (OrderVO orderVO : orders){
            List<OrderDetail> orderDetailList = orderVO.getOrderDetailList();
            String orderDish = "";
            //把一个订单中所有菜品/套餐合并成一个字符串
            for (OrderDetail orderDetail : orderDetailList){
                orderDish = orderDish + (orderDetail.getName()+"×"+orderDetail.getNumber()+";");
            }
            orderVO.setOrderDishes(orderDish);
        }
        Page<OrderVO> p = (Page<OrderVO>)orders;
        return new PageResult(p.getTotal(),p.getResult());
    }

    //商家接单
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        ordersMapper.update(orders);
    }

    //商家拒单
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //根据订单id查看订单状态
        Orders orders1 = ordersMapper.getById(ordersRejectionDTO.getId());
        //若果订单已付款，需要退款
        if(orders1.getPayStatus() == 1){
            //退款
            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
            log.info("拒单退款");
        }
        //更新订单状态
        Orders orders = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .status(Orders.CANCELLED)
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .build();
        ordersMapper.update(orders);
    }

    //商家取消订单
    public void adminCancelOrder(OrdersCancelDTO dto) {
        //根据订单id，查询订单相关信息
        Orders orders = ordersMapper.getById(dto.getId());
        Orders orders1 = new Orders();
        //已付款的订单退款，并更改订单的支付状态为退款
        if(orders.getPayStatus() == 1){
            //退款
            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
            //修改支付状态
            orders1.setPayStatus(Orders.REFUND);
        }
        //把订单状态更改为已取消
        orders1.setId(dto.getId());
        orders1.setStatus(Orders.CANCELLED);
        orders1.setCancelTime(LocalDateTime.now());//取消的时间
        orders1.setCancelReason(dto.getCancelReason());
        //更新订单状态
        ordersMapper.update(orders1);
    }

    //商家派单
    public void deliveryOrder(Long id) {
        //根据id查询订单信息
        Orders orders = ordersMapper.getById(id);
        Orders orders1 = new Orders();
        orders1.setId(id);
        //判断订单状态是否是已接单，不是的话抛出错误
        if(orders.getStatus() != 3){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //把订单状态改为派送
        orders1.setStatus(Orders.DELIVERY_IN_PROGRESS);
        ordersMapper.update(orders1);
    }

    //商家完成订单
    public void completeOrder(Long id) {
        //查询订单的信息
        Orders orders = ordersMapper.getById(id);
        Orders orders1 = new Orders();
        orders1.setId(id);
        //判断订单的状态是否是派送中
        if(null == orders || orders.getStatus() != Orders.DELIVERY_IN_PROGRESS){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //设置订单的状态为完成状态
        orders1.setStatus(Orders.COMPLETED);
        orders1.setDeliveryTime(LocalDateTime.now());//设置送达时间
        //更新订单状态
        ordersMapper.update(orders1);
    }

   //各个状态订单数量统计
    public OrderStatisticsVO statisticsOrder() {
        //查找各个状态及其数量，以map形式返回
        List<Map<Integer, Object>> list = ordersMapper.statisticOrder();
        OrderStatisticsVO vo = new OrderStatisticsVO();
        //遍历集合把对应的状态和数量放入相应位置
        for (Map<Integer, Object> map : list){
            int status = (Integer) map.get("status");
            int count = ((Long)map.get("count")).intValue();//long转化为int类型
            if(status == Orders.TO_BE_CONFIRMED){//待接单
                vo.setToBeConfirmed(count);
            }else if(status == Orders.CONFIRMED){//待派送
                vo.setConfirmed(count);
            }else if(status == Orders.DELIVERY_IN_PROGRESS){//派送中
                vo.setDeliveryInProgress(count);
            }
            System.out.println(map);
        }
        return vo;
    }

    //客户催单
    public void reminder(Long id) {
        //首先查询订单确定订单是否存在以及订单的状态是否是待接单，之后根据情况进行催单
        OrderVO orderVO = ordersMapper.getOrderDetailsById(id);
        if(null == orderVO || orderVO.getStatus() != 2){//订单为空或订单不为带接单状态
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //设置催单信息
        Map map = new HashMap<>();
        map.put("type",2);//2表示催单
        map.put("orderId",id);//订单id
        map.put("content","订单号:"+orderVO.getNumber());//订单号
        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));//催单
    }
}
